package com.ninong.ker.workflow.rest;


import com.ninong.ker.admin.service.ProcessDefinitionService;
import com.ninong.ker.admin.service.dto.ProcessDefXmlDTO;
import com.ninong.ker.admin.service.dto.ProcessDefinitionDTO;
import com.ninong.ker.common.response.CmdResponse;
import com.ninong.ker.common.tools.enums.BusinessEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;


@RestController
@RequestMapping("cmd/v1/definition")
public class ProcessDefinitionController {

    @Autowired
    private ProcessDefinitionService processDefinitionService;


    /**
     * 获取流程定义集合
     *
     * @param dto
     * @return
     */
    @PostMapping
    public ResponseEntity<CmdResponse> list(@RequestBody ProcessDefinitionDTO dto) {
        CmdResponse response = new CmdResponse();
        response.setData(processDefinitionService.listPage(dto));
        return ResponseEntity.ok(response);

    }

    /**
     * 通过stringBPMN添加流程定义
     *
     * @param dto
     * @return
     */
    @PutMapping
    public ResponseEntity<CmdResponse> addDeploymentByString(@RequestBody ProcessDefXmlDTO dto) {
        processDefinitionService.insert(dto.getStringBPMN());
        return ResponseEntity.ok(new CmdResponse());

    }

    /**
     * 获取流程定义XML
     *
     * @param id
     */
    @GetMapping(value = "/{id}")
    public ResponseEntity<CmdResponse> getProcessDefineXML(@PathVariable String id) throws IOException {
        CmdResponse response = new CmdResponse();
        response.setData(processDefinitionService.get(id));
        return ResponseEntity.ok(response);
    }

    /**
     * 删除已经部署成功的流程定义
     * 背后影响的表:
     * act_ge_bytearray
     * act_re_deployment
     * act_re_procdef
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public ResponseEntity<CmdResponse> addDeploymentByString(@RequestBody String[] ids) {
        processDefinitionService.delete(ids);
        CmdResponse response = new CmdResponse();
        response.setMessage(BusinessEnum.DELETE_SUCCESS.getMsg());
        return ResponseEntity.ok(response);

    }

    /**
     * 启动挂起流程流程定义
     *
     * @param dto
     * @return
     */
    @PostMapping("/updateState")
    public ResponseEntity<CmdResponse> updateState(@RequestBody ProcessDefinitionDTO dto) {
        processDefinitionService.updateState(dto);
        CmdResponse response = new CmdResponse();
        return ResponseEntity.ok(response);
    }


    @GetMapping(value = "/getDefinitions/{instanceId}")
    public ResponseEntity<CmdResponse> getDefinitionsByInstanceId(@PathVariable("instanceId") String instanceId){
        CmdResponse response = new CmdResponse();
        response.setData(processDefinitionService.getDefinitionsByInstanceId(instanceId));
        return ResponseEntity.ok(response);
    }
}
